package com.xj.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xj.reggie.common.R;
import com.xj.reggie.entity.User;
import com.xj.reggie.service.SendMailService;
import com.xj.reggie.service.UserService;
import com.xj.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author XJ
 * @Date 2022/10/23 19:22
 * @PackageName:com.xj.reggie.controller
 * @ClassName: UserController
 * @Description: TODO
 * @Version 1.0
 */

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private SendMailService sendMailService;

	/**
	 * 发送邮箱验证码
	 * @param user
	 * @return
	 */
	@PostMapping("/sendMsg")
	public R<String> sendMsg(@RequestBody User user, HttpSession session){
		//获取邮箱号
		String email = user.getEmail();

		if(StringUtils.isNotEmpty(email)){
			//生成随机的4位验证码
			String code = ValidateCodeUtils.generateValidateCode(4).toString();
			log.info("code={}",code);

			//调用sendMailService.sendMail()发送邮件;
//			sendMailService.sendMail(email,code);
			//需要将生成的验证码保存到Session
			session.setAttribute(email,code);
			return R.success("邮箱验证码发送成功!");
		}

		return R.error("邮箱验证码发送失败!");
	}

	@PostMapping("/login")
	public R<User> login(@RequestBody Map map, HttpSession session){
		log.info(map.toString());

		//获取用户填写的邮箱号
		String email = map.get("email").toString();

		//获取用户填写的验证码
		String code = map.get("code").toString();

		//从Session中获取保存的验证码
		Object codeInSession = session.getAttribute(email);

		//进行验证码比对
		if(codeInSession !=null && codeInSession.equals(code)){
			//如果比对成功，说明登录成功

			LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(User::getEmail,email);

			User user = userService.getOne(queryWrapper);
			if(user == null){
				//判断当前邮箱号对应的用户是否为新用户，如果是新用户，就自动完成注册
				user = new User();
				user.setEmail(email);
				user.setStatus(1);
				userService.save(user);
			}

			session.setAttribute("user",user.getId());
			return R.success(user);
		}

		return R.error("验证码验证失败!");
	}

	/**
	 * 退出功能
	 * ①在controller中创建对应的处理方法来接受前端的请求，请求方式为post；
	 * ②清理session中的用户id
	 * ③返回结果（前端页面会进行跳转到登录页面）
	 * @return
	 */
	@PostMapping("/loginout")
	public R<String> logout(HttpServletRequest request){
		//清理session中的用户id
		request.getSession().removeAttribute("user");
		return R.success("退出成功");
	}
}
